from flask import Flask
from redis import StrictRedis
from flask_session import Session
from flask_jsonrpc import JSONRPC
from flask_sqlalchemy import SQLAlchemy
from flask_jsonrpc.site import JSONRPCSite

from apps.settings.dev import DevelopementConfig
from apps.settings.prop import ProductionConfig
from apps.utils.log import init_log

config = {
    "dev": DevelopementConfig,
    "prop": ProductionConfig,
}

# 预设全局变量
redis_store = None
db = SQLAlchemy()
# 创建jsonrpc实例对象
jsonrpc = JSONRPC(app=None, service_url='/api/v1',site=JSONRPCSite(),enable_web_browsable_api=True)

jsonrpc2 = JSONRPC(app=None, service_url='/api/v2',site=JSONRPCSite(), enable_web_browsable_api=True)

def init_app(config_name):
    """项目的初始化功能"""
    app = Flask(__name__)

    # 设置配置类
    Config = config[config_name]

    # 加载配置
    app.config.from_object(Config)

        # redis的链接初始化
    global redis_store
    redis_store = StrictRedis(host=Config.REDIS_HOST, port=Config.REDIS_PORT,db=0)

    # 开启session功能
    Session(app)
    
    # 配置数据库链接
    db.init_app(app)

    # 启动日志
    init_log(Config)

    # jsonrpc注册到app应用对象中
    jsonrpc.init_app(app)
    jsonrpc2.init_app(app)

    return app
